package ufba.mata61.compilador.internal.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;

import ufba.mata61.compilador.app.core.com.IToken;


/**
 *<p> This class is used to manipulate the I/O operation 
 * of the source code file. This class do not intend be extends.   
 *</p>
 *
 * @author Joao Pedro Bittencourt
 *
 */
public class IOOperation {
	
	private final char EOF = (char)-1;
	private boolean isEOF = false;
	private BufferedReader in;
	private boolean buf, bufferize;
	private static char buffer;
	private static String lineBuffer;
	private int line = 0, column = 0; 
	private Vector<String> bufferVec;
	
	/**
	 * Bind a source file with the scanner
	 * 
	 * @param sourceCode path of the source code on disk
	 */
	public IOOperation(String sourceCode) {
		try {
			in = new BufferedReader(new FileReader(sourceCode));
		} catch (FileNotFoundException e) {
			System.err.println("File not found!");
		}
		bufferVec = new Vector<String>();
		bufferize = false;
	}
	
	public void setBufferize(boolean v){
		bufferize = v;
	}
	
	/**
	 * return to previous char scanned
	 */
	public void returnToPreviousChar() {
		if (!isEOF) 
			buf  = true;
		
	}
	
	public int getLine(){
		return line;
	}
	
	public int getColumn(){
		return column;
	}
	
	/**
	 * read the next char of the file
	 * 
	 * @return next char
	 */
	public char getNextChar(){
		char character = (char)-1;
        try {
		   if(!buf){
			   character = (char) in.read();
			   column++;
		   }
		   else{
			   character = buffer;
			   buf = false;
		   }
		   if (character == '\r'){
			   character = getNextChar();
			   column = 0;
			   line++;
		   }
           if (character == EOF) isEOF = true;
        } catch (IOException e) {};
//        System.out.println("-> "+character);
        buffer = character;
        return character;
	}
	
	
	/**
	 * return to previous char scanned
	 */
	public void returnToPreviousToken() {
		if (!isEOF) 
			buf  = true;
		
	}
	
	/**
	 * read the next char of the file
	 * 
	 * @return next char
	 */
	public String getNextToken(){
		String token = EOF+"";
        try {
		   if(!buf){
			   if(!bufferize)
				   token = (String) in.readLine();
			   else{
				   token = bufferVec.firstElement();
				   bufferVec.remove(0);
				   if(bufferVec.isEmpty()) bufferize = false;
			   }
		   }
		   else{
			   token = lineBuffer;
			   buf = false;
		   }
		   if(token.equals(IToken.COMMENT))
			   token = getNextToken();
		   if (token == EOF+"") isEOF = true;
        } catch (IOException e) {};
//        System.out.println("-> "+character);
        lineBuffer = token;
        return token;
	}
	
	public boolean isEOF(){
		return isEOF;
	}

	public void bufferize(String token){
		bufferVec.add(token);
	}
}
